package cn.itsource.interceptor;

import cn.itsource.config.JacksonObjectMapper;
import cn.itsource.rate.RateLimitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

	@Autowired
	private RateLimitService rateLimitService;

	@Resource
	private LoginInterceptor loginInterceptor;

	@Override
	protected void addInterceptors(InterceptorRegistry registry) {


		ArrayList patterns = new ArrayList<>();
		patterns.add("/system/**");
		patterns.add("/system/login");
		patterns.add("/shop/settlement");
		patterns.add("/email/**");
		patterns.add("/user/**");
		patterns.add("/file/**");
		patterns.add("/wechat/**");
		patterns.add("/error");
		patterns.add("/pay/**");
		patterns.add("/dept/**");


		RateLimitInterceptor rateLimitInterceptor = new RateLimitInterceptor();
		rateLimitInterceptor.setRateLimitService(rateLimitService);
		registry.addInterceptor(rateLimitInterceptor).order(2);
		registry.addInterceptor(loginInterceptor)
				.addPathPatterns("/**")
				.excludePathPatterns(patterns)
				.order(1);
	}
	/**
	 * 扩展MVC框架的消息转换器
	 * @param converters
	 */
	@Override
	protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
		//创建消息转换器对象
		MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
		//设置对象转换器
		messageConverter.setObjectMapper(new JacksonObjectMapper());
		//将上面的转换器添加到MVC框架的转换器中
		converters.add(0,messageConverter);
	}
}
